<template>
  <div>
    <div class="title font14 ma30-15">
      <p>基本信息</p>
    </div>
    <!-- 基本信息 -->

    <el-form
      :model="ruleForm"
      :rules="ruleFormRules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm mt20"
    >
      <div class="pa15 bor7 details">
        <div class="clearfix">
          <div class="fr details-but">
            <router-link to=""><el-button @click="$router.back(-1)" class="primary1">返回</el-button></router-link>
          </div>
        </div>
        <el-form-item label="活动标题" prop="activity_id" required>
          <el-select
            v-model="ruleForm.activity_id"
            placeholder="请选择故事所属的活动"
          >
            <el-option
              v-for="item in this.defaultList"
              :key="item.id"
              :label="item.activity.title"
              :value="item.activity.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="故事名称" prop="title" required>
          <el-input
            v-model="ruleForm.title"
            placeholder="请输入故事名称"
          ></el-input>
        </el-form-item>

        <el-form-item
          label="故事封面"
          prop="image"
          class="font12 huodonghaibao"
          required
        >
          <!-- <img src="../../img/2.jpg" alt /> -->
          <el-row :gutter="20">
            <el-col :span="6" class="p_l_no">
              <el-upload
                class="upload-demo"
                drag
                action="#"
                ref="upload"
                :file-list="files"
                :http-request="handleUpload"
                :auto-upload="true"
              >
                <div class="grid-content bg-purple">
                  <img
                    v-if="imageUrl"
                    :src="imageUrl"
                    v-model="ruleForm.image"
                    class="avatar w100"
                  />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </div>
              </el-upload>
            </el-col>
            <el-col :span="6" class="p_lr_100">
              <div class="grid-content bg-purple font12">
                <div class="bg-purple-text">
                  <p class="colred">温馨提示</p>
                  1、图片尺寸 1080*640，.jpg 或 .png格式，不超过 4M
                  <br />2、精美海报有助于增加报名量，并有机会获得强力推荐！
                  <div>
                    <!--el-button @click="CancelUpload">取 消</el-button-->
                    <!--el-button
                      type="primary"
                      class="primary"
                      @click="fileChange"
                      >上传海报</el-button-->
                  </div>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-form-item>

        <el-form-item label="是否公开" prop="is_pub" required>
          <el-radio-group v-model="ruleForm.is_pub">
            <el-radio :label="1" value="1">公开</el-radio>
            <el-radio :label="0" value="0">不公开</el-radio>
          </el-radio-group>
        </el-form-item>
      </div>

      <!--  -->
      <div class="title font14 ma30-15">
        <p>故事内容</p>
      </div>
      <!-- 活动内容 -->
      <div class="pa15 bor7 details-fng">
        <div class="quill-box">
          <template>
            <el-form-item prop="content"  >
              <quill-editor
                v-model="ruleForm.content"
                :options="editorOption"
                ref="content"
              ></quill-editor>
            </el-form-item>
          </template>
        </div>
      </div>
    </el-form>

    <div class="ta mt20">
      <el-button
        type="submit"
        class="baocun"
        @click="handleSubmit">
        保存故事
      </el-button>
    </div>
  </div>
</template>



<style scoped>
/* .el-form-item__content{
  width: 50%;
} */
.avatar.w100 {
  object-fit: cover;
  width: 100% !important;
}
.details {
}
.primary1:hover {
  background: #fff !important;
  color: #4285f4 !important;
}
.p_l_no {
  padding-left: 0 !important;
}
.primary1 {
  margin-bottom: 0.9375rem;
}
.primary1:hover {
  background: transparent !important;
  transition: all 0.6s;
  color: #4285f4;
}
/* .details .demo-ruleForm > div:nth-of-type(2) {
  width: 50%;
} */
.el-form-item__label {
}
.details .demo-ruleForm > div label {
  text-align: left;
  font-size: 0.75rem;
}
.details .line {
  text-align: center;
}
.el-select {
  width: 100%;
}
.details .el-col-20 {
  width: 82.33333%;
  margin-left: 1%;
}
.wid50 {
  width: 50%;
}
.details-fix .el-button {
  padding: 0.3125rem 0.625rem;
  font-size: 0.875rem;
}
.details-fix .el-button--success {
  background: #19a15f;
}
.el-form-item > label {
  text-align: left !important;
}
.details .font12 label {
  text-align: left;
  font-size: 0.75rem;
}
.details-fix-duv .bg-purple {
  border: 1px solid #d8d8d8;
  text-align: center;
  color: #b2b2b2;
  padding: 3rem 0;
}
.details-fix-duv .bg-purple:hover {
  border-color: #4285f4;
}
.details-fix-duv .el-col-5 {
  width: 20%;
  margin-bottom: 1.25rem;
}
.details-fix-duv .bg-purple p:nth-of-type(1) {
  color: #545556;
  margin: 1.25rem 0 0.625rem;
}
.details-fix-duv .bg-purple img {
  width: 6.375rem;
  object-fit: cover;
}
.quill-box .quill-editor {
  overflow: hidden;
  font-style: initial;
}
.ql-toolbar.ql-snow + .ql-container.ql-snow {
  height: 100% !important;
  position: relative;
  /* min-height: 14.0625rem;
  font-style: initial; */
}
.ql-editor {
}
.details-but .el-button {
  padding: 0.75rem 2rem;
}

.ql-editor {
  height: 400px;
}
.ql-container {
  height: 400px;
}@media (max-width:767px) {
  .p_l_no {
    padding-left: 10px !important;
  }
}
</style>

<script>
import { quillEditor, Quill } from "vue-quill-editor";
const toolbarOptions = [
  ["bold", "italic", "underline", "strike"],
  ["blockquote", "code-block"],
  [{ list: "ordered" }, { list: "bullet" }],
  [{ indent: "-1" }, { indent: "+1" }],
  [{ color: [] }, { background: [] }],
  [{ align: [] }],
  ["link", "image"],
  ["clean"],
  [{ size: ["small", false, "large", "huge"] }],
  [{ header: [1, 2, 3, 4, 5, 6, false] }],
  [{ font: [] }],
];

export default {
  data() {
    return {
      content: ``,
      imageUrl: "",
      defaultList: [],
      ruleForm: [],
      ruleFormRules: {
        title: [
          {
            type: "string",
            required: true,
            message: "故事名称必填",
            trigger: "blur",
          },
          { max: 30, message: "故事名称长度不能超过30位" },
        ],
        image: [
          {
            type: "string",
            required: true,
            message: "图片要上传",
            trigger: "blur",
          },
        ],
        is_pub: [{ required: true, message: "是否公开", trigger: "blur" }],
        activity_id: [
          { required: true, message: "活动标题必填", trigger: "blur" },
        ],
        content: [{ required: true, message: "内容必填", trigger: "blur" }],
      },
      files: [],
      editorOption: {
        placeholder: "内容编辑",
        modules: {
          toolbar: {
            container: toolbarOptions,
            // ...
          },
        },
      },
    };
  },

  methods: {
    onEditorReady(editor) {
      // 准备编辑器
    },
    onEditorBlur() {}, // 失去焦点事件
    onEditorFocus() {}, // 获得焦点事件
    onEditorChange() {}, // 内容改变事件
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("图片尺寸 1080*640，.jpg 或 .png格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传图片尺寸不能超过 4M!");
      }
      return isJPG && isLt2M;
    },
    getActivityJoin() {
      var that = this;
      this.$axios
        .get(this.$api + "//api/my/activityjoin")
        .then(function (response) {
          that.defaultList = response.data.data.data;
          //console.log(that.defaultList);
        })
        .catch(function (error) {
          //console.log(error);
        });
    },
    //提交
    handleSubmit() {
      //console.log(this.ruleForm);
      this.$nextTick(() => {
        this.$refs.ruleForm.validate(async (valid) => {
          if (valid) {
            //console.log(this.ruleForm);
            //定义一个json示例
            if (this.$route.query.id) {
              var url = this.$api + "/api/story/edit";
              var jsons = {
                id: this.$route.query.id,
                activity_id: this.ruleForm.activity_id,
                title: this.ruleForm.title,
                image: this.ruleForm.image,
                content: this.ruleForm.content,
                is_pub: this.ruleForm.is_pub,
              };
            } else {
              var url = this.$api + "/api/story/add";
              var jsons = {
                activity_id: this.ruleForm.activity_id,
                title: this.ruleForm.title,
                image: this.ruleForm.image,
                content: this.ruleForm.content,
                is_pub: this.ruleForm.is_pub,
              };
            }

            var that = this;

            this.$axios
              .post(url, jsons)
              .then((res) => {
                //console.log(res.data);
                if (res.data.code == 1) {
                  that.$message({
                    message: res.data.msg,
                    type: "success",
                  });
                  that.$router.push("/my_story");
                } else {
                  that.$message.error(res.data.msg);
                }
              })
              .catch((Error) => {
                //console.log(Error);
              });
          }
        });
      })
    },
    //上传文件开始
    handleUpload(raw) {
      this.files.push(raw.file);
      this.fileChange();
      // //console.log(files);
    },
    async fileChange() {
      if (this.files.length > 1) {
        //this.$message.warning(`当前限制只能上传选择 1 个文件`);
        return;
      } else {
      }
      const loading = this.$loading({
        lock: true,
        text: "上传中...",
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.7)",
      });
      this.$refs.upload.submit(); // 这里是执行文件上传的函数，其实也就是获取我们要上传的文件
      let random = Math.random();
      let formData = new FormData();
      // formData.append("file", param.file);
      //formData.append("user_id", localStorage.user_id);
      this.files.forEach(function (file) {
        formData.append("file", file); // 因为要上传多个文件，所以需要遍历一下才行
        //不要直接使用我们的文件数组进行上传，你会发现传给后台的是两个Object
      });
      let res = await this.$axios.post(
        this.$api + `/api/common/upload`,
        formData
      );
      ////console.log(res);
      // JSON.parse(res)
      if (res.data.code == 1) {
        this.$refs.upload.clearFiles();
        this.files = [];
        let objList = [];
        loading.close();
        this.imageUrl = this.$api + res.data.data.url;
        //this.ruleForm.image = res.data.data.url;
        this.$set(this.ruleForm,'image',res.data.data.url);
        //console.log('111', this.ruleForm.image);
      } else {
        loading.close();
        this.$message.error("上传文件失败" + res.data.msg);
      }
    },
    handExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    CancelUpload() {
      this.files = [];
      this.$refs.upload.clearFiles();
    },
    handFileSuccess(file) {
      //console.log(file);
      this.files = [];
      this.$refs.upload.clearFiles();
    },
    handleRemove(file, fileList) {
      // //console.log(file, fileList);
      this.files = fileList;
    },
    beforeRemove(file, fileList) {
      // //console.log(file, fileList);
    },
    //上传文件结束
    getInfo() {
      if (!this.$route.query.id) {
        return false;
      }
      var that = this;
      this.$axios
        .get(this.$api + "//api/story/detail?id=" + this.$route.query.id)
        .then(function (response) {
          that.ruleForm = response.data.data;
          that.imageUrl = that.$api + response.data.data.image;

          //console.log("info", response.data.data);
        })
        .catch(function (error) {
          //console.log(error);
        });
    },
  },
  mounted() {
    this.getActivityJoin();
    this.getInfo();
  },
  components: {
    "quill-editor": quillEditor,
  },
};
</script>
